package com.health.mapp.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.health.commons.PropertiesService;
import com.health.pay.tencent.ResponseHandler;

/**
 * 微信回调处理
 * 注：日志未记
 * */
public class WXPayNotifyService extends HttpServlet {

	private static final String PARTNER_KEY = PropertiesService.getString("wx.key");
	private static final String partner = PropertiesService.getString("wx.mchId");
	private static final Logger logger = Logger.getLogger(WXPayNotifyService.class);

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.info("-------------微信支付来消息啦------------");

		String userAgent = request.getHeader("user-agent");
		String referer = request.getHeader("referer");
		logger.debug("userAgent:"+userAgent +";referer:"+referer);
		ResponseHandler resHandler = new ResponseHandler(request, response);
		resHandler.setKey(PARTNER_KEY);
		// 判断签名
		if (resHandler.isTenpaySign()) {

			// 获取返回参数
			String retcode = resHandler.getParameter("return_code");
			if (null != retcode && retcode.equals("SUCCESS")) {

				String resultCode = resHandler.getParameter("result_code");

				if (null != resultCode && resultCode.equals("SUCCESS")) {
					logger.info("订单查询成功");
					// 取结果参数做业务处理
					String out_trade_no = resHandler.getParameter("out_trade_no");//商户订单号
					//logger.info("out_trade_no:"+ out_trade_no);
					String transaction_id = resHandler.getParameter("transaction_id");//微信订单号
		
					String total_fee=resHandler.getParameter("total_fee");
				
					
					logger.info("success 后台通知成功");
					resHandler.sendToCFT("SUCCESS");
					
				/*	EPayCashPayment payment = new EPayCashPayment();
					
					payment.setBankCashIdno(transaction_id);
					payment.setPaycashTotal(MappMath.div(Double.valueOf(total_fee), 100d,2)); 
					payment.setReceiveData(JSONObject.fromObject(resHandler.getAllParameters()).toString());
					
					PayActionServerImpl impl = new PayActionServerImpl();
					impl.updatePayCashPaymentLog(out_trade_no, payment);
					
					try {
						impl.payAction(out_trade_no,Constant.CONSTANTS_PAYMENT_WEIXIN);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/
				}
			}

		} else {
			logger.error("通知签名验证失败");
		}

	}
	
	public static void main(String[] args) {
		
	}
}
